$(function () {

  //Construct the game world.
  for (var ix = 0; ix < 16; ix++) {
    $('.game-box').append('<div class="game-block" id="block-' + ix + '"></div>')
  }

  function redrawBlock(worldline) {
    for (var ix = 0; ix < 16; ix++) {
      var elem = $('#block-' + ix);
      if (worldline[ix] > 0) {
        elem.text(worldline[ix]);
      } else {
        elem.text('');
      }
      elem.removeClass();
      if (worldline[ix] > 2048) {
        elem.addClass('game-block tile tile-super');
      } else {
        elem.addClass('game-block tile tile-' + worldline[ix]);
      }
    }
  }

  LGM.genRandomWorld(4);
  console.log(LGM.getGameworldLine());
  redrawBlock(LGM.getGameworldLine());

  $(document).on('keydown', function (e) {
    if (e.keyCode >= 37 && e.keyCode <= 40) {
      LGM.go(e.key);
      redrawBlock(LGM.getGameworldLine());
      $('.score-board').text("总积分：" + LGM.getScore());
    }
  });

  var gamebox = document.querySelector(".game-box");
  var hammertime = new Hammer(gamebox, {});
  hammertime.on('swipe', function (ev) {
    switch (ev.direction) {
      case Hammer.DIRECTION_DOWN: {
        LGM.go('ArrowDown');
        break;
      }
      case Hammer.DIRECTION_UP: {
        LGM.go('ArrowUp');
        break;
      }
      case Hammer.DIRECTION_LEFT: {
        LGM.go('ArrowLeft');
        break;
      }
      case Hammer.DIRECTION_RIGHT: {
        LGM.go('ArrowRight');
        break;
      }
      default: {
        //do nothing.
      }
    }
    redrawBlock(LGM.getGameworldLine());
    $('.score-board').text("总积分：" + LGM.getScore());
  });

  hammertime.get('swipe').set({ direction: Hammer.DIRECTION_ALL });
});